package storage.metadata;

import storage.record.*;
import storage.tx.Transaction;
class ViewMgr {
	private static final int MAX_VIEWDEF = 100;
	TableMgr tblMgr;
	
	public ViewMgr(boolean isNew, TableMgr tblmgr, Transaction tx){
		this.tblMgr = tblmgr;
		if(isNew){
			Schema sch = new Schema();
			sch.addStringField("viewname", TableMgr.MAX_NAME);
			sch.addStringField("viewdef", MAX_VIEWDEF);
			tblMgr.createTable("viewcat", sch, tx);
		}
	}
	
	public void createView(String vname, String vdef, Transaction tx){
		TableInfo ti = tblMgr.getTableInfo("viewcat", tx);
		RecordFile rf = new RecordFile(ti, tx);
		rf.insert();
		rf.setString("viewname", vname);
		rf.setString("viewdef", vdef);
		rf.close();
	}
	
	public String getViewDef(String vname, Transaction tx){
		TableInfo ti = tblMgr.getTableInfo("viewcat", tx);
		RecordFile rf = new RecordFile(ti, tx);
		while(rf.next()){
			if (rf.getString("viewname").equals(vname))
				return rf.getString("viewdef");
		}
		return null;
	}

}
